<template>
  <div class="news-add-or-update">
    <el-drawer :title="this.rowData ? '编辑通知' : '新增通知'" :visible.sync="drawer" custom-class="demo-drawer" direction="rtl" size="88%">
      <div class="demo-drawer__content">
        <div :style="cardHeightStyle" class="rightScrollNone">
          <el-form size="mini" :model="dataForm" :rules="rules" ref="vendorRuleForm">
            <el-row>
              <el-col :span="24">
                <el-form-item label="通知标题：" prop="title" :label-width="formLabelWidth">
                  <el-input autocomplete="off" type="text" v-model="dataForm.title"></el-input>
                </el-form-item>
              </el-col>
              <el-col>
                <el-form-item label="发送范围：" prop="is_all" :label-width="formLabelWidth">
                  <el-radio-group v-model="dataForm.is_all">
                    <el-radio :label="1">全部企业</el-radio>
                    <el-radio :label="2">指定企业</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>

              <el-col :span="24" v-if="dataForm.is_all == 2">
                <el-form-item label="选择主体：" prop="mainBodyID" :label-width="formLabelWidth">
                  <el-select v-model="dataForm.mainBodyID" @change="changeMainBodyId" placeholder="全部主体" style="width: 100%">
                    <el-option v-for="item in mainBodyArr" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="dataForm.is_all == 2">
                <el-form-item label="选择区域：" prop="areaID" :label-width="formLabelWidth">
                  <el-select v-model="dataForm.areaID" placeholder="全部区域" style="width: 100%" @change="changeAreaId">
                    <el-option v-for="item in areaIdArr" :key="item.id" :label="item.name" :value="item.id"> </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="dataForm.is_all == 2">
                <el-form-item label="选择企业：" :label-width="formLabelWidth">
                  <el-transfer
                    style="text-align: left; display: inline-block"
                    v-model="dataForm.qyIds"
                    filterable
                    :titles="['源企业', '目标企业']"
                    :format="{
                      noChecked: '${total}',
                      hasChecked: '${checked}/${total}',
                    }"
                    @change="handleChange"
                    :data="qyAll"
                  >
                  </el-transfer>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-form-item label="内容：" prop="content" :label-width="formLabelWidth">
                  <tinymce v-model="dataForm.content" :height="500" v-if="drawer_tinymce" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div class="demo-drawer__footer">
          <el-button size="mini" @click="cancelForm">取 消</el-button>
          <el-button size="mini" :loading="loading" @click="dataFormSubmit(2)" type="primary">发布</el-button>
          <el-button size="mini" :loading="loading" @click="dataFormSubmit(1)" type="success">存为草稿</el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import Tinymce from '@/components/Tinymce'
import { areaArrApi, mainBodiesApi } from '../../../api/baseInfo'
import { AddNoticeApi, EditNoticeApi } from '../../../api/notice'
import { qyAllApi } from '../../../api/commonApi'
import jsCookie from 'js-cookie'

export default {
  data() {
    const generateData = (_) => {
      const data = []
      for (let i = 1; i <= 15; i++) {
        data.push({
          key: i,
          label: `备选项 ${i}`,
          disabled: i % 4 === 0,
        })
      }
      return data
    }
    return {
      areaIdArr: [],
      mainBodyArr: [],
      data: generateData(),
      value4: [],
      renderFunc(h, option) {
        return (
          <span>
            {option.key} - {option.label}
          </span>
        )
      },
      dataForm: {
        id: '',
        mainBodyID: '',
        areaID: '',
        title: '',
        is_all: 1,
        qyIds: [],
      },
      qyAll: [],
      rowData: null,
      formLabelWidth: '120px',
      loading: false,
      drawer: false,
      drawer_tinymce: false,
      rules: {
        title: [{ required: true, message: '请输入通知标题', trigger: 'blur' }],
        is_all: [{ required: true, message: '请选择发送范围', trigger: 'blur' }],
      },
      dialogImageUrl: '',
      dialogVisible: false,
    }
  },
  components: { Tinymce },
  mounted() {
    this.getAreaArrFun()
    this.getMainBodiesFun()
  },
  computed: {
    cardHeightStyle() {
      let documentClientHeight = document.body.clientHeight
      const height = documentClientHeight - 80 - 80
      return {
        height: height + 'px',
        'overflow-y': 'scroll',
        'padding-right': '20px;',
      }
    },
  },
  methods: {
    changeAreaId() {
      this.getQyAllFun()
    },
    getQyAllFun() {
      this.qyAll = []
      const pa = {
        main_body_id: this.dataForm.mainBodyID,
        area_id: this.dataForm.areaID,
      }
      qyAllApi(pa).then((res) => {
        // this.qyAll = res.result
        res.result.forEach((element) => {
          this.qyAll.push({
            key: element.qyId__id,
            label: element.qyId__name,
            disabled: false,
          })
          // console.log('qyAll',this.qyAll)
        })
      })
    },
    handleChange(value, direction, movedKeys) {
      // console.log(value, direction, movedKeys);
      // console.log("value4", this.value4)
    },
    changeMainBodyId() {
      this.getAreaArrFun()
      this.getQyAllFun()
    },
    getAreaArrFun() {
      areaArrApi({ main_body_id: this.dataForm.mainBodyID }).then((res) => {
        this.areaIdArr = res.result
      })
    },
    getMainBodiesFun() {
      mainBodiesApi({}).then((res) => {
        this.mainBodyArr = res.result
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    editorValChangHandle(content) {
      this.dataForm.desc = content
    },
    reportAdd(params) {
      return AddNoticeApi(params)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('保存成功')
          }
        })
        .catch((res) => {
          this.$message.error('保存失败')
        })
    },
    reportUpdate(params) {
      return EditNoticeApi(params)
        .then((res) => {
          if (res.code == 200) {
            this.$message.success('保存成功')
          }
        })
        .catch((res) => {
          this.$message.error('保存失败')
        })
    },

    dataFormSubmit(v) {
      this.$refs.vendorRuleForm.validate((flag) => {
        if (flag) {
          const data = this.dataForm
          this.dataForm.label = v
          if (this.dataForm.is_all == 1) {
            // 发送范围选择全部企业
            data.qyIds = JSON.stringify([])
            data.mainBodyID = ''
            data.areaID = ''
          } else {
            data.qyIds = this.dataForm.qyIds.length > 0 ? JSON.stringify(this.dataForm.qyIds) : JSON.stringify([])
          }
          var request = this.rowData ? this.reportUpdate(data) : this.reportAdd(data)
          request
            .then((d) => {
              this.cancelForm()
              this.$emit('refreshList')
            })
            .catch((d) => {
              this.cancelForm()
            })
        }
      })
    },
    cancelForm() {
      this.cleanInfo()
      this.loading = false
      this.drawer = false
      this.drawer_tinymce = false
    },
    open(row, role) {
      if (this.drawer) {
        return
      }
      this.rowData = row || null
      this.drawer = true
      this.drawer_tinymce = true
      this.openHook()
    },
    clearData() {
      this.$refs.vendorRuleForm.resetFields()
    },
    cleanInfo() {
      clearTimeout(this.timeOutCount)
      this.dataForm.content = ''
    },
    openHook() {
      this.$nextTick((a) => {
        this.clearData()
        // this.$refs.quillEdit.open(this.rowData);
        if (this.rowData) {
          // 修改
          for (let key in this.dataForm) {
            if (key == 'qyIds') {
              this.dataForm[key] = typeof this.dataForm[key] == 'string' ? JSON.parse(this.rowData[key]) : this.dataForm[key]
              // console.log('--------->', this.dataForm[key])
            } else {
              this.dataForm[key] = this.rowData[key]
            }
          }
          if (this.dataForm.areaID) {
            this.getQyAllFun()
          }
        } else {
          this.loading = false
        }
      })
    },
  },
}
</script>
<style lang="scss">
.news-add-or-update {
  .icon-m {
    font-size: 25px;
    margin-left: 10px;

    position: relative;
    top: 4px;
    color: #03a9f4;
    cursor: pointer;
  }

  .el-tag {
    position: relative;
    right: 5px;
    z-index: 1;
    height: 40px;
    line-height: 40px;
    border-radius: 0 5px 5px 0;
    padding-left: 15px;
  }

  .my-email {
    .el-input__inner {
      border-radius: 5px 0 0 5px;
    }
  }
}

/*

  */

.fileInput {
  padding-right: 0;
}
</style>
